package epsi.mobile.views;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.google.android.gms.maps.model.LatLng;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import epsi.mobile.adapters.StoreListViewAdapter;
import epsi.mobile.business.StoreProcess;
import epsi.mobile.constants.ConfigurationConstants;
import epsi.mobile.entities.Store;
import epsi.mobile.helpers.GPSTracker;
import epsi.mobile.helpers.NetworkHelper;
import epsi.mobile.helpers.ProximitySearchHelper;
import epsi.mobile.storelocator.R;

public class StoreListActivity extends Activity implements OnClickListener 
{
	private ListView			listView;
	private ArrayList<Store>	storeList;
	
    private GPSTracker 			gps;
    
    private Bundle 				getRequest;
    private String 				request;
    
    private double 				currentLatitude;
    private double 				currentLongitude;
    
    private StoreProcess 		storeProcess;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.storelist);
                
        this.storeList	= new ArrayList<Store>();
        this.listView	= (ListView)findViewById(R.id.storeList);
        
        this.initList();
        
        if(this.storeList.isEmpty())
        {
            setContentView(R.layout.nodata);
        }
        
        StoreListViewAdapter adapter = new StoreListViewAdapter(this, this.storeList);

        this.listView.setAdapter(adapter);
        this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
            	Intent detailsIntent = new Intent(StoreListActivity.this, StoreDetailsActivity.class);
            	detailsIntent.putExtra("storeId",storeList.get(position).getStoreId());
    	    	startActivity(detailsIntent);
            }
        });            
    }
    
    private void initList() 
	{
		storeProcess = new StoreProcess(getApplicationContext());
		
		getRequest = getIntent().getExtras(); //Get the request
		request = getRequest.getString("listRequest");
		
		if(request.equals(ConfigurationConstants.MapProximityRequest)) // If it's a proximity Research
		{		
			// check if GPS enabled     
            	currentLatitude = GPSTracker.latitude;
            	currentLongitude = GPSTracker.longitude;
            	
            	this.storeList	 = storeProcess.getNearbyStores(currentLatitude,currentLongitude);
		}
		else // If it's a user research
		{
		    if(!request.equals("")) // If the value searched not null
		    {
		        try
                {
		            if (NetworkHelper.isOnline(this)) // If we have access to network
                    {
		                ProximitySearchHelper prox = new ProximitySearchHelper(this);
		                prox.execute(request);
		                LatLng lat = prox.get();
		                if(lat!=null)
		                {
		                    this.storeList = storeProcess.getNearbyStores(lat.latitude, lat.longitude);
		                }
		                else
		                {
		                    this.storeList = new ArrayList<Store>(); 
		                }
	                }
	                else
	                {
	                    try
	                    {
	                       Integer.parseInt(request.substring(0, 2));
	                        this.storeList = this.storeProcess.getStoreByPostalCode(request.substring(0, 2));	                        
	                    } 
	                    catch(NumberFormatException e) 
	                    {
	                        this.storeList = this.storeProcess.getStoreByText(request);
	                    }
	                }   
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (ExecutionException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
		    }
		    else // If no value entered by the user, return all stores
		    {
		    	this.storeList = this.storeProcess.getAllStores();
		    }			
		}	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list, menu);
		return true;
	}
	
    public boolean onOptionsItemSelected(MenuItem item) 
    {
		switch (item.getItemId()) {
		case R.id.action_map:
			Intent listIntent = new Intent(StoreListActivity.this, StoreMapActivity.class);
			listIntent.putExtra("mapRequest",request);
	    	startActivity(listIntent);
	    	StoreListActivity.this.finish();
		  break;	
		}
		return true;
	}

	@Override
	public void onClick(DialogInterface arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
}
